/**
 * cbp
 * @param {() => Promise} callBack
 * @returns
 */
module.exports.cbp = function (callBack) {
  return (req, file, cb) => {
    callBack(req, file)
      .then((e) => {
        cb(null, e)
      })
      .catch((e) => {
        cb(e, false)
      })
  }
}

const { rename, readFile } = require('fs/promises')
const { createWriteStream } = require('fs')

const { join, extname } = require('path')
const { v4 } = require('uuid')
const md5 = require('md5')

module.exports.storageMD5 = class {
  dest = ''
  constructor({ dest }) {
    this.dest = dest
  }
  _handleFile(req, file, cb) {
    const ext = extname(file.originalname)
    const path = join(this.dest, v4() + '.uploading')
    var outStream = createWriteStream(path)

    file.stream.pipe(outStream)
    outStream.on('error', cb)
    outStream.on('finish', async () => {
      const file = await readFile(path)
      console.log(file);
      const name = md5(file) + ext
      console.log('path', join(this.dest, name))
      await rename(path, join(this.dest, name))
      cb(null, {
        path,
        name,
        size: outStream.bytesWritten,
      })
    })
  }
  _removeFile(req, file, cb) {
    fs.unlink(file.path, cb)
  }
}
